package com.linkage.jz.bankruptcy.activity.Project;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.CreateZQOneProjectActivity;
import com.linkage.jz.bankruptcy.adapter.CourtViewAdapter;
import com.linkage.jz.bankruptcy.adapter.MyProListViewAdapter;
import com.linkage.jz.bankruptcy.bean.CourtInfo;
import com.linkage.jz.bankruptcy.bean.MyProInfo;
import com.linkage.jz.bankruptcy.bean.ProTalkReply;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.PublicLongNoticeDialog;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.RecyclerViewNoBugLinearLayoutManager;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.base.BaseActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildLongClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemLongClickListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class SearchCourtActivity extends BaseActivity implements BGAOnRVItemLongClickListener, BGAOnRVItemClickListener, BGAOnItemChildClickListener, BGAOnItemChildLongClickListener {

    private EditText editKeyword;
    private TextView cancel;
    private RecyclerView projectList;
    private CourtViewAdapter adapter;

    private PublicNoticeDialog noticeDialog;
    private PublicLongNoticeDialog noticelxDialog;
    private RelativeLayout empty_layout;

    private ShapeLoadingDialog mShapeLoadingDialog;
//    private View empty_layout;

    List<CourtInfo> dataList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarMode(false);
        setContentView(R.layout.activity_search_court);
        initView();
        mShapeLoadingDialog = new ShapeLoadingDialog(SearchCourtActivity.this);
    }

    private void initView() {
        dataList = new ArrayList<>();
        editKeyword = (EditText) findViewById(R.id.edit_keyword);
        empty_layout = findViewById(R.id.empty_layout);
        empty_layout.setVisibility(View.GONE);
        cancel = (TextView) findViewById(R.id.cancel);
        projectList = (RecyclerView) findViewById(R.id.project_item);
        projectList.setLayoutManager(new RecyclerViewNoBugLinearLayoutManager(SearchCourtActivity.this));
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        editKeyword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                getData();
            }
        });

//        editKeyword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
////                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//                    //关闭软键盘
//                final String str = editKeyword.getText().toString().trim();
//                if ("".equalsIgnoreCase(str)) {
//
//                    return false;
//                }
//                    getData();
////                    return true;
////                }
//                return false;
//            }
//        });

        adapter = new CourtViewAdapter(projectList,SearchCourtActivity.this);

        adapter.setOnRVItemClickListener(this);
        adapter.setOnRVItemLongClickListener(this);
        adapter.setOnItemChildClickListener(this);
        adapter.setOnItemChildLongClickListener(this);
        adapter.setData(dataList);
        projectList.setAdapter(adapter);
        projectList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (RecyclerView.SCROLL_STATE_DRAGGING == newState) {
                    adapter.closeOpenedSwipeItemLayoutWithAnim();
                }
            }
        });
    }


    /**
     * 获取数据
     */
    public void getData() {
        final String str = editKeyword.getText().toString();
        if (TextUtils.isEmpty(str)) {

            return;
        }


        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }

//        mShapeLoadingDialog.setLoadingText("提交信息中...");
//        mShapeLoadingDialog.setCanceledOnTouchOutside(false);
//        mShapeLoadingDialog.show();

        Observable<JsonObject> observable;

        observable = Network
                    .getAPIService()
                    .getCourtList( str);


        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
//                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonObject objectdata = json.get("data").getAsJsonObject();
                        JsonArray courtList = objectdata.get("courtList").getAsJsonArray();


                        List<CourtInfo> list = CourtInfo.parse(courtList);
                            dataList.clear();
                            dataList.addAll(list);
                        if (list == null || list.size() == 0) {
                            empty_layout.setVisibility(View.VISIBLE);
                        }
                        else{
                            empty_layout.setVisibility(View.GONE);
                        }

                            adapter.notifyItemRangeChanged(0,100);
//                        editKeyword.setText(str);
//                        editKeyword.requestFocus();
//                        editKeyword.setSelection(editKeyword.getText().length());


//                                editKeyword.requestFocus();
//                        editKeyword.setFocusable(true);
//
//                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//
//                        imm.showSoftInputFromInputMethod(editKeyword.getWindowToken(),0);

                    }

                    @Override
                    public void onCompleted() {

                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
//                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
//        OkHttpClient okHttpClient = new OkHttpClient();
////        HashMap<String, String> params = new HashMap<String, String>();
//        Random random = new Random();
//        String rom = random.nextLong() + "";
//        String timestamp = System.currentTimeMillis() + "";
//        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
//        RequestBody requestBody = new FormBody.Builder()
//                .add("appid", "1000000001")
//                .add("nonce", rom)
//                .add("timestamp", timestamp)
//                .add("userToken", userToken)
//                .add("token", BankruptcyApp.tokeninfo.getToken())
//                .add("pageNumber", "1")
//                .add("pageSize", "100")
//                .add("keywords", str)
//                .build();
//
//        String url = Consts.WEBURL_GETMYPRO;
//        Request request = new Request.Builder()
//                .url(url)
//                .post(requestBody)
//                .build();
//
//        okHttpClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                e.printStackTrace();
//                dataList.clear();
//                adapter.notifyDataSetChanged();
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                final String str = response.body().string();
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            JSONObject object = new JSONObject(str);
//                            JSONObject objdata = object.getJSONObject("data");
//                            MyProInfo[] array = new Gson().fromJson(objdata.optString("list"), MyProInfo[].class);
//                            List<MyProInfo> list = Arrays.asList(array);
//                            dataList.clear();
//                            dataList.addAll(list);
//                            adapter.notifyDataSetChanged();
//                        } catch (Exception ex) {
//                            ex.printStackTrace();
//                            dataList.clear();
//                            adapter.notifyDataSetChanged();
//                        }
//
//                        if (dataList == null || dataList.size() == 0)
//                            empty_layout.setVisibility(View.VISIBLE);
//                        else
//                            empty_layout.setVisibility(View.GONE);
//                    }
//                });
//            }
//        });
    }

    @Override
    public boolean onRVItemLongClick(ViewGroup parent, View itemView, int position) {
        return true;
    }

    @Override
    public void onRVItemClick(ViewGroup parent, View itemView, int position) {
        try {
            if (position < adapter.getData().size()) {
                CourtInfo model = adapter.getItem(position);
                if (model != null) {
                    Intent intent = new Intent(SearchCourtActivity.this, CreateProjectDetailTwoActivity.class);
                    intent.putExtra("courtname", model.getCourtName());
                    intent.putExtra("courtid", model.getId());
                    setResult(RESULT_OK, intent);

                    finish();

                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void onItemChildClick(ViewGroup parent, View childView, int position) {

    }



    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.ll_close:
                    noticeDialog.dismiss();
                    break;
                case R.id.btn_chancel_notice:
                    noticeDialog.dismiss();
                    noticelxDialog = new PublicLongNoticeDialog(SearchCourtActivity.this, onClickListener,
                            1, "", "",
                            "", "");
                    noticelxDialog.show();
                    break;
                case R.id.ll_close_lx:
                case R.id.btn_chancel_notice_lx:
                    noticelxDialog.dismiss();
                    break;

                case R.id.btn_save_notice_lx:
                    Boolean flag = noticelxDialog.cb_agree.isChecked();
                    if (flag) {
                        noticelxDialog.dismiss();
//                        CreateZQOneProjectActivity.start(SearchCourtActivity.this);
                    } else {
                        showToast("请同意后再确认");
                    }
                    break;

            }
        }
    };

    @Override
    public boolean onItemChildLongClick(ViewGroup parent, View childView, int position) {
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {
            return true;
        }
        return false;
    }


}
